#pragma once

#include<iostream>
#include<queue>
#include<pthread.h>

#define defaultnum 5

template<class T>
class blockqueue
{
private:
    std::queue<T> _q;
    int _cap = defaultnum;
    pthread_mutex_t _lock;
    pthread_cond_t _c_cond;
    pthread_cond_t _p_cond;
public:
    //构造
    blockqueue(int cap = defaultnum)
        :_cap(cap)
    {
        pthread_mutex_init(&_lock,nullptr);
        pthread_cond_init(&_c_cond,nullptr);
        pthread_cond_init(&_p_cond,nullptr);
    }
    //析构
    ~blockqueue()
    {
        pthread_mutex_destroy(&_lock);
        pthread_cond_destroy(&_c_cond);
        pthread_cond_destroy(&_p_cond);
    }

    void push(const T& in)
    {
        pthread_mutex_lock(&_lock);
        if(_cap == _q.size())
        {
            pthread_cond_wait(&_p_cond,&_lock);
        }
        _q.push(in);
        pthread_cond_signal(&_c_cond);
        pthread_mutex_unlock(&_lock);
    }

    T pop()
    {
        pthread_mutex_lock(&_lock);
        while(_q.size() == 0)
        {
            pthread_cond_wait(&_c_cond,&_lock);
        }

        T data = _q.front();
        _q.pop();
        pthread_cond_signal(&_p_cond);
        pthread_mutex_unlock(&_lock);

        return data;
    }
}; 